package online.dgyj.zigbee;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.nle.mylibrary.claimer.zigbee.FourChannelValConvert;
import com.nle.mylibrary.databus.DataBus;
import com.nle.mylibrary.databus.DataBusFactory;
import com.nle.mylibrary.databus.ReciveData;
import com.nle.mylibrary.device.GenericConnector;
import com.nle.mylibrary.device.ZigBee3;
import com.nle.mylibrary.device.listener.ConnectResultListener;
import com.nle.mylibrary.enums.zigBee.ZigBeeSensorType;
import com.nle.mylibrary.util.DataTools;

import java.util.concurrent.TimeUnit;

@SuppressLint("DefaultLocale")
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Handler handler;
    private DataBus dataBus;
    private GenericConnector genericConnector;
    private String ip;
    private int port;
    private boolean Control = false;

    private TextView sensor1Text, sensor2Text, sensor3Text, sensor4Text, sensor5Text, sensor6Text, sensor7Text, sensor8Text, sensor9Text, sensor10Text;
    private TextView sensor1Value, sensor2Value, sensor3Value, sensor4Value, sensor5Value, sensor6Value, sensor7Value, sensor8Value, sensor9Value, sensor10Value;
    private ConstraintLayout sensor10;
    private EditText IPEdit, PortEdit;
    private Switch RTUSwitch;
    private Button LinkBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        bind();


    }

    /**
     * 初始化视图
     * 此方法主要适配通用UI,正常不推荐
     */
    private void InitView() {
        sensor1Text.setText("温度");
        sensor2Text.setText("湿度");
        sensor3Text.setText("光照");
        sensor4Text.setText("人体");
        sensor5Text.setText("火焰");
        sensor6Text.setText("IN1");
        sensor7Text.setText("IN2");
        sensor8Text.setText("IN3");
        sensor9Text.setText("IN4");
        sensor10Text.setText("继电器");
        sensor10Value.setText("关闭");
    }

    /**
     * 实例化控件
     */
    private void bind() {

        handler = new Handler(Looper.getMainLooper());

        sensor1Text = findViewById(R.id.sensor1Text);
        sensor2Text = findViewById(R.id.sensor2Text);
        sensor3Text = findViewById(R.id.sensor3Text);
        sensor4Text = findViewById(R.id.sensor4Text);
        sensor5Text = findViewById(R.id.sensor5Text);
        sensor6Text = findViewById(R.id.sensor6Text);
        sensor7Text = findViewById(R.id.sensor7Text);
        sensor8Text = findViewById(R.id.sensor8Text);
        sensor9Text = findViewById(R.id.sensor9Text);
        sensor10Text = findViewById(R.id.sensor10Text);

        sensor1Value = findViewById(R.id.sensor1Value);
        sensor2Value = findViewById(R.id.sensor2Value);
        sensor3Value = findViewById(R.id.sensor3Value);
        sensor4Value = findViewById(R.id.sensor4Value);
        sensor5Value = findViewById(R.id.sensor5Value);
        sensor6Value = findViewById(R.id.sensor6Value);
        sensor7Value = findViewById(R.id.sensor7Value);
        sensor8Value = findViewById(R.id.sensor8Value);
        sensor9Value = findViewById(R.id.sensor9Value);
        sensor10Value = findViewById(R.id.sensor10Value);

        sensor10 = findViewById(R.id.sensor10);

        IPEdit = findViewById(R.id.IPEdit);
        PortEdit = findViewById(R.id.PortEdit);

        RTUSwitch = findViewById(R.id.RTUSwitch);

        LinkBtn = findViewById(R.id.LinkBtn);

        InitView();

        // 事件处理
        LinkBtn.setOnClickListener(this);
        sensor10.setOnClickListener(this);

        RTUSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { // 事件处理
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    IPEdit.setHint("SerialName");
                    PortEdit.setHint("Baud");
                    IPEdit.setText("");
                    PortEdit.setText("");
                } else {
                    IPEdit.setHint("IP");
                    PortEdit.setHint("Port");
                    IPEdit.setText("");
                    PortEdit.setText("");
                }
            }
        });
    }

    /**
     * 获取两位小数
     *
     * @param val Value
     * @return 两位Double
     */
    private Double GetTwoBitDouble(Double val) {
        return Double.parseDouble(String.format("%.2f", val));
    }

    /**
     * 更新视图
     *
     * @param textView 目标TextView
     * @param val      更新的Value
     */
    private void UpdateView(TextView textView, double val) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                textView.setText(String.valueOf(val));
            }
        });
    }

    /**
     * 数据解析
     */
    private void GetData() {
        dataBus.setReciveDataListener(new ReciveData() {
            @Override
            public String getReciveData(byte[] bytes) {
                try {
                    ZigBee3 zigBee3 = new ZigBee3(bytes);
                    // 温湿度
                    if (zigBee3.sensorType() == ZigBeeSensorType.TEM_HUM.getCode()) {
                        UpdateView(sensor1Value, GetTwoBitDouble(zigBee3.getVal0()));
                        UpdateView(sensor2Value, GetTwoBitDouble(zigBee3.getVal1()));
                    }
                    // 光照
                    else if (zigBee3.sensorType() == ZigBeeSensorType.LIGHT.getCode()) {
                        UpdateView(sensor3Value, GetTwoBitDouble(zigBee3.getVal0()));
                    }
                    // 人体
                    else if (zigBee3.sensorType() == ZigBeeSensorType.PERSON.getCode()) {
                        Log.d("Body", String.valueOf(zigBee3.getVal0()));
                        UpdateView(sensor4Value, GetTwoBitDouble(zigBee3.getVal0()));
                    }
                    // 火焰
                    else if (zigBee3.sensorType() == ZigBeeSensorType.FIRE.getCode()) {
                        UpdateView(sensor5Value, GetTwoBitDouble(zigBee3.getVal0()));
                    }
                    // 四输入的数据解析需要配合FourChannelValConvert类来完成
                    else if (zigBee3.sensorType() == ZigBeeSensorType.FOUR_ENTER.getCode()) {
                        Log.d("IN1", String.valueOf(zigBee3.getVal0()));
                        Log.d("IN2", String.valueOf(zigBee3.getVal1()));
                        Log.d("IN3", String.valueOf(zigBee3.getVal2()));
                        Log.d("IN4", String.valueOf(zigBee3.getVal3()));
                        UpdateView(sensor6Value, GetTwoBitDouble(FourChannelValConvert.getTemperature(zigBee3.getVal0())));
                        UpdateView(sensor7Value, GetTwoBitDouble(FourChannelValConvert.getHumidity(zigBee3.getVal1())));
                        UpdateView(sensor8Value, GetTwoBitDouble(zigBee3.getVal2()));
                        UpdateView(sensor9Value, GetTwoBitDouble(zigBee3.getVal3()));
                    }
                }catch (ArrayIndexOutOfBoundsException e){
                    Log.i("ZigBee Data",e.toString());
                }
                return null;
            }
        });
    }

    /**
     * 控制继电器
     *
     * @param serialNum 短地址 单联 141d
     * @param choose    指令
     *                  单联 开 0x21
     *                  关 0x22
     *                  双联 一开 二关   0x21
     *                  全关       0x22
     *                  一关 二开   0x12
     *                  全开       0x11
     */
    private void SendControl(int serialNum, byte choose) {
        try {
            genericConnector.ZigbeeControl(serialNum, choose, null);
        } catch (Exception e) {
            Log.e("ZigBee Control", e.toString());
        }
    }


    @Override
    public void onClick(View v) {
        // 连接
        if (v.getId() == R.id.LinkBtn) {
            if (genericConnector == null) {
                ip = IPEdit.getText().toString();
                port = Integer.parseInt(PortEdit.getText().toString());
                if (RTUSwitch.isChecked()) {
                    dataBus = DataBusFactory.newSerialDataBus(Integer.parseInt(ip), port);
                    GetData();
                    genericConnector = new GenericConnector(dataBus, new ConnectResultListener() {
                        @Override
                        public void onConnectResult(boolean b) {
                            if (b) {
                                Log.i("Rtu Status", "Link OK");
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        IPEdit.setEnabled(false);
                                        PortEdit.setEnabled(false);
                                        RTUSwitch.setEnabled(false);
                                        LinkBtn.setText("DISC");
                                        Toast.makeText(getApplication(), "连接成功", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            } else {
                                Log.e("Rtu Status", "Link Error");
                                genericConnector = null;// 销毁
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getApplicationContext(), "连接失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }
                    });
                } else {
                    dataBus = DataBusFactory.newSocketDataBus(ip, port);
                    GetData();
                    genericConnector = new GenericConnector(dataBus, new ConnectResultListener() {
                        @Override
                        public void onConnectResult(boolean b) {
                            if (b) {
                                Log.i("Tcp Status", "Link OK");
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        IPEdit.setEnabled(false);
                                        PortEdit.setEnabled(false);
                                        RTUSwitch.setEnabled(false);
                                        LinkBtn.setText("DISC");
                                        Toast.makeText(getApplication(), "连接成功", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            } else {
                                Log.e("Tcp Status", "Link Error");
                                genericConnector = null;// 销毁
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getApplicationContext(), "连接失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }
                    });
                }
            } else {
                IPEdit.setEnabled(true);
                RTUSwitch.setEnabled(true);
                PortEdit.setEnabled(true);
                RTUSwitch.setEnabled(true);

                LinkBtn.setText("Link");

                Toast.makeText(getApplication(), "断开连接", Toast.LENGTH_SHORT).show();

                // 销毁
                genericConnector.stopConnect();
                genericConnector = null;
            }
        }
        // 继电器控制
        else if (v.getId() == R.id.sensor10) {
            if (Control) {
                Control = false;
                SendControl(0x141d, (byte) 0x22);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        sensor10Value.setText("关闭");
                    }
                });
            } else {
                Control = true;
                SendControl(0x141d, (byte) 0x21);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        sensor10Value.setText("开启");
                    }
                });
            }
        }
    }
}